using System;
using System.Collections.Generic;
using System.Text;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Expression.Entity;
using T.FAS.Runtime.Expression.Service;
using T.FAS.Runtime.ScheduleJob.SPI;
using T.ServiceComponent.Kernel.Service;

namespace T.FAS.Runtime.ScheduleJob.Engine
{
    public class ServerJSJobEngine : IScheduleJobImpEngineProxy, IScheduleJobExecuteHandler, IScheduleJobDataResultBuilder
    {
        public void AfterExecute(ScheduleJobExecContext execContext, TResult result)
        {
        }

        public void BeforeExecute(ScheduleJobExecContext execContext)
        {
        }

        public TResult BuildScheduleJobDataResult(ScheduleJobExecContext context, object dataResult)
        {
            return new TResult();
        }

        public object Execute(ScheduleJobExecContext context)
        {
            var sJob = context.ScheduleJobMetaData as Metadata.Entity.ScheduleJob.ScheduleJob;

            if (sJob == null)
                throw new FasException(ScheduleJobRTPExceptionCode.ScheduleJobMetadataNotExistError, CommonStringClassEngine.ActionJobEngine_NotValidSchedulaJobMetaData);
            if (sJob.JobType != Metadata.Entity.ScheduleJob.JobType.JSSCript)
                throw new FasException(ScheduleJobRTPExceptionCode.ScheduleJobExecuteError, string.Format(CommonStringClassEngine.ServerJSJobEngine_Execute1,sJob.Code));
            if (string.IsNullOrEmpty(sJob.JobContent))
                throw new FasException(ScheduleJobRTPExceptionCode.ScheduleJobExecuteError, string.Format(CommonStringClassEngine.ServerJSJobEngine_NotDefineTaskScript,sJob.Code));
            var jsContent = sJob.JobContent; 
            var parameters = context.Instance.Data.GetDictionary();
            var result = ExprService.GetInstance.JSExecute(jsContent, parameters);
            if (result.State == ResultState.Fail)
            {
                throw new FasException(ScheduleJobRTPExceptionCode.ScheduleJobExecuteError, string.Format(CommonStringClassEngine.ServerJSJobEngine_ErrorRowNum,result.RowNum,result.ErrMsg));
            }
            return result;
        }

        public void ExecuteError(ScheduleJobExecContext execContext, Exception exception)
        {
        }
    }
}
